package com.medusa.aps.business.modules.security.mp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medusa.aps.business.model.pagination.Page;
import com.medusa.aps.business.modules.security.model.input.UserRoleQueryPara;
import com.medusa.aps.business.modules.security.mp.entity.Role;
import com.medusa.aps.business.modules.security.mp.entity.UserRole;
import com.medusa.aps.business.modules.security.mp.mapper.UserRoleMapper;
import com.medusa.aps.business.modules.security.mp.service.IUserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author: xianhui.yu
 **/
@Service
@Transactional
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {


    @Override
    public void listPage(Page<UserRole> page, UserRoleQueryPara filter) {
        page.setRecords(baseMapper.selectUserRoles(page, filter));
    }

    @Override
    public List<UserRole> list(UserRoleQueryPara filter) {
        return baseMapper.selectUserRoles(filter);
    }

    @Override
    public Integer insert(UserRole para) {
        if (para.getId() != null) {
            baseMapper.updateById(para);
        } else {
            baseMapper.insert(para);
        }
        return para.getId();
    }

    @Override
    public void saveUserRole(UserRoleQueryPara para) {
        Integer roleId = para.getRoleId();
        String userIds = para.getUserIds();
        baseMapper.deleteByRoleId(roleId);
        if (StringUtils.isNotBlank(userIds)) {
            String[] userIdArrays = userIds.split(",");
            for (String userId : userIdArrays) {
                UserRole userRole = new UserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(Long.parseLong(userId));
                baseMapper.insert(userRole);
            }
        }
    }

    @Override
    public List<Role> selectRoleByUserId(Long userId) {
        return baseMapper.selectRoleByUserId(userId);
    }

}
